package gemini.castor.ui.client.page.content.home.search.form;

import gemini.basic.dto.SearchDistributorCriteria;
import gemini.basic.dto.SearchDistributorResult;
import gemini.castor.ui.client.ServiceCatalog;
import gemini.castor.ui.client.mvp.callback.AbstractAsyncCallback;
import gemini.castor.ui.client.mvp.single.CastorWidgetDisplay;
import gemini.castor.ui.client.mvp.single.CastorWidgetPresenter;
import gemini.castor.ui.client.page.RootEvent;
import gemini.castor.ui.client.utils.PlaceConstants;

import java.util.ArrayList;
import java.util.List;

import ch.elca.gwt.mvp.client.EventBus;
import ch.elca.gwt.mvp.client.place.Place;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.inject.Inject;

public class SearchFormPresenter extends
		CastorWidgetPresenter<SearchFormPresenter.Display> {

	@Inject
	public SearchFormPresenter(Display display, EventBus globalEventBus) {
		super(display, globalEventBus);
	}

	public interface Display extends CastorWidgetDisplay {

		HasClickHandlers getSearchClickHandlers();
		boolean isValidate();
		void showResult(List<SearchDistributorResult> resultPersons);
		SearchDistributorCriteria getCriteria();
	}

	public static final Place PLACE = new Place(PlaceConstants.PLACE_FIND_SOMEONE);
	
	

	@Override
	protected void onBind() {

		registerHandler(display.getSearchClickHandlers().addClickHandler(
				new ClickHandler() {
					public void onClick(ClickEvent event) {
						if(display.isValidate()){
							searchPerson();
						}
					}
				}));
		
		display.loadData();
	}


	protected void searchPerson() {
		SearchDistributorCriteria criteria = display.getCriteria();
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		ServiceCatalog.getDistributorService().findDistributor(criteria,
				new AbstractAsyncCallback<ArrayList<SearchDistributorResult>>() {

					@Override
					public void onSuccess(
							ArrayList<SearchDistributorResult> result) {
						eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
						display.showResult(result);
					}
				});
	}


	@Override
	public Place getPlace() {
		return PLACE;
	}
}
